package core

import (
	"context"
	"fmt"
	"gin-mvc/dao"
	"gin-mvc/jobs"
	"gin-mvc/pkg/core/load"
	"gin-mvc/pkg/setting"
	"gin-mvc/routers"
	"gin-mvc/tasks"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func RunServer() {

	load.SetUp()
	defer dao.CloseMysqlConn()
	defer dao.CloseRedisConn()

	// 设置运行模式
	gin.SetMode(setting.ServerSetting.RunMode)

	// 消费队列
	jobs.Consumer()

	// 开启定时任务
	go tasks.Setup()

	// 初始化路由
	router := routers.InitRouter()

	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", setting.ServerSetting.HttpPort),
		Handler:        router,
		ReadTimeout:    setting.ServerSetting.ReadTimeout,
		WriteTimeout:   setting.ServerSetting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen：%v\n", err)
		}
	}()

	msg := fmt.Sprintf("服务器启动成功，ServerName: %s, Addr: http://0.0.0.0:%d", setting.AppSetting.AppName, setting.ServerSetting.HttpPort)
	log.Println(msg)

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
